package com.wenwen.social.domain.service.Impl;

import com.wenwen.social.domain.model.PersonLine;
import com.wenwen.social.domain.service.PersonLineService;
import com.wenwen.social.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static com.wenwen.social.constant.PersonLineConstant.PERSON_LINE_REDIS_PRE;
import static java.util.stream.Collectors.toList;

@Service
public class PersonLineServiceImpl implements PersonLineService{
	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public void add(Long uid,PersonLine PersonLine){
		ZSetOperations zSetOperations = redisTemplate.opsForZSet();
		zSetOperations.add(getKey(uid),PersonLine.getMessageId(),PersonLine.getTime());
		return;
	}

	@Override
	public List<PersonLine> query(Long uid,Integer page, Integer num) {
		ZSetOperations zSetOperations = redisTemplate.opsForZSet();
		PageUtil pageUtil = new PageUtil(page, num);
		Set<DefaultTypedTuple> range = zSetOperations.reverseRangeWithScores(getKey(uid), pageUtil.getStartNum(), pageUtil.getEndNum());
		if (range == null || range.isEmpty()) {
			return new ArrayList<>();
		}

		List<PersonLine> result = range.stream()
				.map(t -> new PersonLine( (Long)t.getValue(),t.getScore().longValue()))
				.collect(toList());
		return result;
	}

	@Override
	public Integer del(Long uid,Long msgId) {
		ZSetOperations zSetOperations = redisTemplate.opsForZSet();
		Long remove = zSetOperations.remove(getKey(uid), msgId);
		return remove.intValue();
	}

	@Override
	public Long count(Long uid) {
		ZSetOperations zSetOperations = redisTemplate.opsForZSet();
		return zSetOperations.zCard(getKey(uid));
	}

	private String getKey(Long uid) {
		return PERSON_LINE_REDIS_PRE+uid;
	}
}
